package com.icim.twyd.exporter.service;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.icim.core.service.IFtpTwydService;
import com.icim.csot.exporter.tx.csotshipping.CsotShippingO;
import com.icim.dao.RetBoxDao;
import com.icim.dao.RetCusBoxDao;
import com.icim.dao.RetCusPrdDao;
import com.icim.dao.RetPrdGrdInfoDao;
import com.icim.dao.RetPrdInfoDao;
import com.icim.dao.RetWoDao;
import com.icim.entity.Ret_box;
import com.icim.entity.Ret_cus_box;
import com.icim.entity.Ret_cus_prd;
import com.icim.entity.Ret_prd_grd_info;
import com.icim.entity.Ret_prd_info;
import com.icim.entity.Ret_wo;
import com.icim.twyd.exporter.xmlentity.TwydBoxXmlEntityOK;
import com.icim.twyd.exporter.xmlentity.TwydCellXmlEntityOK;
import com.icim.twyd.exporter.xmlentity.TwydCellXmlEntitySC;
import com.icim.twyd.exporter.xmlentity.TwydMessageXmlEntityOK;
import com.icim.twyd.exporter.xmlentity.TwydMessageXmlEntitySC;
import com.icim.util.FileUtil;
import com.icim.util.TimeUtil;
import com.icim.util.XmlConvertUtil;

@Service
public class TwydShippingDataService {

    private final Logger logger = LoggerFactory.getLogger(TwydShippingDataService.class);
    @Resource
    private RetBoxDao retBoxDao;

    @Resource
    private RetPrdInfoDao retPrdInfoDao;

    @Resource
    private RetCusPrdDao retCusPrdDao;

    @Resource
    private RetPrdGrdInfoDao retPrdGrdInfoDao;

    @Resource
    private RetCusBoxDao retCusBoxDao;
    
    @Resource 
    private RetWoDao retWoDao;

    @Resource
    private IFtpTwydService ftpTwydService;

    public String subMainProc(String palletId) throws Exception {
        String rtnMsg = "";
        try {
            logger.info(palletId);
            rtnMsg =  subMainProc2(palletId);
        } catch (Exception e) {
            logger.error(e.toString());
            CsotShippingO outTrx = new CsotShippingO();
            outTrx.setTrx_id("CSOTSHIPPING");
            outTrx.setType_id("O");
            outTrx.setRtn_code("9999999");
            outTrx.setRtn_mesg(e.toString());
            rtnMsg = outTrx.toString();
            throw e;
        }
        return rtnMsg;
    }

    public String subMainProc2(String palletId) throws Exception {

        CsotShippingO outTrx = new CsotShippingO();
        outTrx.setTrx_id("CSOTSHIPPING");
        outTrx.setType_id("O");
        outTrx.setRtn_code("0000000");
        outTrx.setRtn_mesg("SUCCESS");

        if (StringUtils.isEmpty(palletId)) {
            outTrx.setRtn_code("0000002");
            outTrx.setRtn_mesg("栈板ID不能为空");
            return XmlConvertUtil.obj2Xml(outTrx, "transaction");
        }

        // 根据palletId找到箱子
        List<Ret_box> retBoxList = retBoxDao.getBoxList(palletId);
        if (retBoxList.isEmpty()) {
            outTrx.setRtn_code("999999");
            outTrx.setRtn_mesg("can not find any box by pallet id");
            return XmlConvertUtil.obj2Xml(outTrx, "transaction");
        }

        List<String> boxIdList = new ArrayList<String>();
        boolean isSc = false;
        for (Ret_box ret_box : retBoxList) {
          List<Ret_prd_info> retPrdInfoList = retPrdInfoDao.getSheetList(ret_box.getBox_id());
          if ("NG".equals(retPrdInfoList.get(0).getGrade()) || "RS".equals(retPrdInfoList.get(0).getGrade())) {
            if (StringUtils.isNotBlank(ret_box.getShip_box_id())) {
              boxIdList.add(ret_box.getShip_box_id());
            }
          }else {
            boxIdList.add(ret_box.getBox_id());
          }
          if ("SC".equals(retPrdInfoList.get(0).getGrade())) {
            isSc = true;
          }
        }

        List<Ret_cus_box> mtrlBoxList = retCusBoxDao.getMtrlBoxList(boxIdList);
        Map<String, Ret_cus_box> mtrlBoxMap = new HashMap<String, Ret_cus_box>();
        for (Ret_cus_box retCusPrdIn : mtrlBoxList) {
            mtrlBoxMap.put(retCusPrdIn.getBoxid(), retCusPrdIn);
        }

        List<File> fileList = new ArrayList<File>();
        if (isSc) {
          TwydMessageXmlEntitySC messageXmlEntitySC = new TwydMessageXmlEntitySC();
          messageXmlEntitySC.setMESSAGE_ID("Z0F_OEM_SCRAP");
          List<TwydCellXmlEntitySC> cellList = new ArrayList<TwydCellXmlEntitySC>();
          for (Ret_box retBox : retBoxList) {
            logger.info("233boxId:"+retBox.getBox_id()+";shipBoxId:"+retBox.getShip_box_id());
            // 根据箱子找到玻璃
            List<Ret_prd_info> retPrdInfoList = retPrdInfoDao.getSheetList(retBox.getBox_id());
            if ("NG".equals(retPrdInfoList.get(0).getGrade()) || "RS".equals(retPrdInfoList.get(0).getGrade())) {
                String xmlFileName = null;
                String xml = null;
                TwydMessageXmlEntityOK messageXmlEntityOK =
                    configXmlOk(palletId, mtrlBoxMap, retBox, retPrdInfoList);
                
                xml = XmlConvertUtil.obj2Xml1(messageXmlEntityOK, "MESSAGE");
                logger.info(xml);

                String localPath = ftpTwydService.getFtpConfigure().getLocalHistoryGzPath();
                xmlFileName = localPath + "/" + messageXmlEntityOK.getBOX().getBOXID() + ".XML";
                
                FileUtil.sting2File(xmlFileName, xml);
                File gzFile = new File(xmlFileName);
                fileList.add(gzFile);
                logger.info("233生成本地文件成功："+xmlFileName);
                logger.info("233待上传文件数量："+fileList.size());
            }else{
            	List<TwydCellXmlEntitySC> cells =
                        configXmlSc(palletId, mtrlBoxMap, retBox, retPrdInfoList);
                cellList.addAll(cells);
            }
          }
          if (cellList.isEmpty()) {
			return XmlConvertUtil.obj2Xml(outTrx, "transaction");
          }
          messageXmlEntitySC.setCELL(cellList);
          String xml = XmlConvertUtil.obj2Xml2(messageXmlEntitySC, "MESSAGE");
          logger.info(xml);

          String localPath = ftpTwydService.getFtpConfigure().getLocalHistoryGzPath();
          
          Random random=new Random();// 定义随机类
          
          String xmlFileName = localPath + "/SCRP_" + TimeUtil.getRvTime()+random.nextInt(10) + ".XML";
          
          
          FileUtil.sting2File(xmlFileName, xml);
          // 压缩位gz包

          //GzCompressUtil.compress(new File(xmlFileName));
          // 上传ftp

          // String gzFileName = xmlFileName + ".gz";
          File gzFile = new File(xmlFileName);
          fileList.add(gzFile);
          logger.info("233生成本地文件成功："+xmlFileName);
          logger.info("233待上传文件数量："+fileList.size());
        }else {
          for (Ret_box retBox : retBoxList) {
            logger.info("233boxId:"+retBox.getBox_id()+";shipBoxId:"+retBox.getShip_box_id());
            // 根据箱子找到玻璃
            List<Ret_prd_info> retPrdInfoList = retPrdInfoDao.getSheetList(retBox.getBox_id());
            String xmlFileName = null;
            String xml = null;
            TwydMessageXmlEntityOK messageXmlEntityOK =
                configXmlOk(palletId, mtrlBoxMap, retBox, retPrdInfoList);
            
            xml = XmlConvertUtil.obj2Xml1(messageXmlEntityOK, "MESSAGE");
            logger.info(xml);

            String localPath = ftpTwydService.getFtpConfigure().getLocalHistoryGzPath();
            xmlFileName = localPath + "/" + messageXmlEntityOK.getBOX().getBOXID() + ".XML";
            
            FileUtil.sting2File(xmlFileName, xml);
            // 压缩位gz包

            //GzCompressUtil.compress(new File(xmlFileName));
            // 上传ftp

            // String gzFileName = xmlFileName + ".gz";
            File gzFile = new File(xmlFileName);
            fileList.add(gzFile);
            logger.info("233生成本地文件成功："+xmlFileName);
            logger.info("233待上传文件数量："+fileList.size());
          }
        }
        
        
      logger.info("233所有本地文件生成成功！！！");  
      try {
        if (!fileList.isEmpty()) {
          logger.info("233开始连接FTP.....");  
          ftpTwydService.connect();
          logger.info("233成功连接FTP！！！！");  
          for (File file : fileList) {
            logger.info("233开始上传文件："+file.getName()+".......");  
            ftpTwydService.uploadFile(file,ftpTwydService.getFtpConfigure().getFtpExportPath());
            logger.info("233成功上传文件："+file.getName()+"！！！！"); 
          }
          logger.info("233所有文件上传成功！！！");  
          logger.info("233开始关闭FTP.....");  
          ftpTwydService.disconnectFtp();
          logger.info("233成功关闭FTP！！！！");  
        }
      } catch (Exception exception) {
        exception.printStackTrace();
        logger.error("233FTP连接异常："+exception.getMessage());
        throw exception;
      }

      return XmlConvertUtil.obj2Xml(outTrx, "transaction");
    }

    private TwydMessageXmlEntityOK configXmlOk(String palletId,
        Map<String, Ret_cus_box> mtrlBoxMap, Ret_box retBox, List<Ret_prd_info> retPrdInfoList) {
    	Collections.sort(retPrdInfoList);
      TwydMessageXmlEntityOK messageXmlEntityOK = new TwydMessageXmlEntityOK();
      TwydBoxXmlEntityOK boxXmlEntityOK = new TwydBoxXmlEntityOK();
      messageXmlEntityOK.setMESSAGE_ID("Z0F_OEM_RETURN");
      // BOX
      if ("NG".equals(retPrdInfoList.get(0).getGrade()) || "RS".equals(retPrdInfoList.get(0).getGrade())) {
        boxXmlEntityOK.setBOXID(StringUtils.isBlank(retBox.getShip_box_id()) ? "" : retBox.getShip_box_id());
      }else {
        boxXmlEntityOK.setBOXID(retBox.getBox_id());
      }
      
      if ("NG".equals(retPrdInfoList.get(0).getGrade()) || "RS".equals(retPrdInfoList.get(0).getGrade())) {
        boxXmlEntityOK.setCELLSIZE("");//14.1 产品尺寸
	    boxXmlEntityOK.setMODEL_NO("");//A030JAN01.4 客户机种，回传 AUO 的值
	    boxXmlEntityOK.setCELLSITE("");
	    boxXmlEntityOK.setPALLET_NO(palletId);
        boxXmlEntityOK.setBOXNO("Z0F");
        boxXmlEntityOK.setARRAYPARTNO("");
        boxXmlEntityOK.setITEMNO("");//良品、可出货报废回传沃格产后型号， IQC NG 回传客户的来料型号
        boxXmlEntityOK.setMODULE_SITE("DW");
        
        String sheetId = retPrdInfoList.get(0).getPrd_seq_id();
          if (StringUtils.contains(sheetId, "_")) {
            sheetId = sheetId.split("_")[0];
          }
        List<Ret_cus_prd> retCusPrdList = retCusPrdDao.getPrdList(sheetId);
        if (!retCusPrdList.isEmpty()) {
      	  List<Ret_cus_box> retCusBoxList = retCusBoxDao.getMtrlBox(retCusPrdList.get(0).getBoxid());
      	  if (!retCusBoxList.isEmpty()) {
      		  boxXmlEntityOK.setCELLSIZE(retCusBoxList.get(0).getCellsize());//14.1 产品尺寸
        		  boxXmlEntityOK.setMODEL_NO(retCusBoxList.get(0).getModel_no());//A030JAN01.4 客户机种，回传 AUO 的值
        		  boxXmlEntityOK.setCELLSITE(retCusBoxList.get(0).getCellsite());
        		  boxXmlEntityOK.setPALLET_NO(palletId);
            	  boxXmlEntityOK.setBOXNO("Z0F");
            	  boxXmlEntityOK.setARRAYPARTNO(retCusBoxList.get(0).getArraypartno());
            	  if ("NG".equals(retPrdInfoList.get(0).getGrade())) {
            		  boxXmlEntityOK.setITEMNO(retCusBoxList.get(0).getItemno());
            	  }
      	  }
        }
      }else {
        boxXmlEntityOK.setITEMNO("");//良品、可出货报废回传沃格产后型号， IQC NG 回传客户的来料型号
        if(!mtrlBoxMap.isEmpty() && mtrlBoxMap.get(retBox.getBox_id()) != null){
      	  boxXmlEntityOK.setCELLSIZE(mtrlBoxMap.get(retBox.getBox_id()).getCellsize());//14.1 产品尺寸
        }else {
      	  boxXmlEntityOK.setCELLSIZE("");//14.1 产品尺寸
        }
        if(!mtrlBoxMap.isEmpty() && mtrlBoxMap.get(retBox.getBox_id()) != null){
      	  boxXmlEntityOK.setMODEL_NO(mtrlBoxMap.get(retBox.getBox_id()).getModel_no());//A030JAN01.4 客户机种，回传 AUO 的值
        }else {
      	  boxXmlEntityOK.setMODEL_NO("");//A030JAN01.4 客户机种，回传 AUO 的值
        }
        boxXmlEntityOK.setMODULE_SITE("DW");
        if(!mtrlBoxMap.isEmpty() && mtrlBoxMap.get(retBox.getBox_id()) != null){
      	  boxXmlEntityOK.setCELLSITE(mtrlBoxMap.get(retBox.getBox_id()).getCellsite());
        }else {
      	  boxXmlEntityOK.setCELLSITE("");
        }
        boxXmlEntityOK.setPALLET_NO(palletId);
        boxXmlEntityOK.setBOXNO("Z0F");
        if(!mtrlBoxMap.isEmpty() && mtrlBoxMap.get(retBox.getBox_id()) != null){
      	  boxXmlEntityOK.setARRAYPARTNO(mtrlBoxMap.get(retBox.getBox_id()).getArraypartno());
        }else {
      	  boxXmlEntityOK.setARRAYPARTNO("");
        }
      }
      
      List<TwydCellXmlEntityOK> cellXmlEntityOKList = new ArrayList<TwydCellXmlEntityOK>();

      for (Ret_prd_info retPrdInfo : retPrdInfoList) {
        String sheetId = retPrdInfo.getPrd_seq_id();
        if (StringUtils.contains(sheetId, "_")) {
          sheetId = sheetId.split("_")[0];
        }
        List<Ret_cus_prd> retCusPrdList = retCusPrdDao.getPrdList(sheetId);
        
        if (!"NG".equals(retPrdInfo.getGrade())) {
          String soId = retPrdInfo.getSo_id_fk();
          List<Ret_wo> retSoList = retWoDao.getWo(soId);
          if (!retSoList.isEmpty() && retSoList.get(0) != null) {
            boxXmlEntityOK.setITEMNO(retSoList.get(0).getMdl_id_fk());//良品、可出货报废回传沃格产后型号， IQC NG 回传客户的来料型号
          }else {
            boxXmlEntityOK.setITEMNO("");//良品、可出货报废回传沃格产后型号， IQC NG 回传客户的来料型号
          }
        }
        
        TwydCellXmlEntityOK cellXmlEntityOK = new TwydCellXmlEntityOK();
        if (!retCusPrdList.isEmpty() && retCusPrdList.get(0) != null) {
          cellXmlEntityOK.setLOT_NO(retCusPrdList.get(0).getLot_no());
        }else {
          cellXmlEntityOK.setLOT_NO("");
        }
        if (!retCusPrdList.isEmpty() && retCusPrdList.get(0) != null) {
          cellXmlEntityOK.setWO_ID(retCusPrdList.get(0).getWo_id());
        }else {
          cellXmlEntityOK.setWO_ID("");
        }
        if (!retCusPrdList.isEmpty() && retCusPrdList.get(0) != null) {
          cellXmlEntityOK.setCELL_SITE(retCusPrdList.get(0).getCell_site());
        }else {
          cellXmlEntityOK.setCELL_SITE("");
        }
        cellXmlEntityOK.setCELLID(sheetId);
        cellXmlEntityOK.setSHEETNO(sheetId);
        cellXmlEntityOK.setCELLSEQ(retPrdInfo.getMtrl_slot_no_fk());
        if (!retCusPrdList.isEmpty() && retCusPrdList.get(0) != null) {
          cellXmlEntityOK.setCELLGRADE(retCusPrdList.get(0).getCellgrade());
        }else {
          cellXmlEntityOK.setCELLGRADE("");
        }
        if (!retCusPrdList.isEmpty() && retCusPrdList.get(0) != null) {
          cellXmlEntityOK.setCELLLOTNO(retCusPrdList.get(0).getCelllotno());
        }else {
          cellXmlEntityOK.setCELLLOTNO("");
        }
        if (!retCusPrdList.isEmpty() && retCusPrdList.get(0) != null) {
          cellXmlEntityOK.setARRAYLOTNO(retCusPrdList.get(0).getArraylotno());
        }else {
          cellXmlEntityOK.setARRAYLOTNO("");
        }
        if (!retCusPrdList.isEmpty() && retCusPrdList.get(0) != null) {
          cellXmlEntityOK.setARRAYSITE(retCusPrdList.get(0).getArraysite());
        }else {
          cellXmlEntityOK.setARRAYSITE("");
        }
        if (!retCusPrdList.isEmpty() && retCusPrdList.get(0) != null) {
          cellXmlEntityOK.setLOTTYPE(retCusPrdList.get(0).getLottype());
        }else {
          cellXmlEntityOK.setLOTTYPE("");
        }
        String grade = "F";
        if ("OK".equals(retPrdInfo.getGrade()) || "LY".equals(retPrdInfo.getGrade()) || "CR".equals(retPrdInfo.getGrade())) {
          grade = "O";
        }
        cellXmlEntityOK.setCHIPGRADE(grade);
        if (!retCusPrdList.isEmpty() && retCusPrdList.get(0) != null) {
          cellXmlEntityOK.setQTY(retCusPrdList.get(0).getQty());
        }else {
          cellXmlEntityOK.setQTY("");
        }
        if (!retCusPrdList.isEmpty() && retCusPrdList.get(0) != null) {
          cellXmlEntityOK.setIS_WARNING(retCusPrdList.get(0).getIs_warning());
        }else {
          cellXmlEntityOK.setIS_WARNING("");
        }
        // 拼凑layout_ox
        List<Ret_prd_grd_info> gradeList = retPrdGrdInfoDao.getGrade(retPrdInfo.getPrd_seq_id());
        if (!gradeList.isEmpty()) {
          String ox_info = gradeList.get(0).getPrd_seq_grd();
          int cnt = ox_info.length();
          StringBuffer buffer = new StringBuffer();
          for (int i = 0; i < cnt; i++) {
            char c = ox_info.charAt(i);
            if (c == '0' || c == 'O' || c == 'o') {
                buffer.append("O");
            } else {
                buffer.append("X");
            }
          }
          cellXmlEntityOK.setJUDGE_MODE(buffer.toString());
        }else {
          cellXmlEntityOK.setJUDGE_MODE("");
        }
        if (!retCusPrdList.isEmpty() && retCusPrdList.get(0) != null) {
          cellXmlEntityOK.setABNORMAL_CODE(retCusPrdList.get(0).getAbnormal_code());
        }else {
          cellXmlEntityOK.setABNORMAL_CODE("");
        }
        if (!retCusPrdList.isEmpty() && retCusPrdList.get(0) != null) {
          cellXmlEntityOK.setFEOL_FAB_CODE(retCusPrdList.get(0).getFeol_fab_code());
        }else {
          cellXmlEntityOK.setFEOL_FAB_CODE("");
        }
        if (!retCusPrdList.isEmpty() && retCusPrdList.get(0) != null) {
          cellXmlEntityOK.setBEOL_FAB_CODE(retCusPrdList.get(0).getBeol_fab_code());
        }else {
          cellXmlEntityOK.setBEOL_FAB_CODE("");
        }
        cellXmlEntityOK.setDEFECT_CODE("");
        cellXmlEntityOK.setPNC_CODE("");
        cellXmlEntityOKList.add(cellXmlEntityOK);
        boxXmlEntityOK.setCELL(cellXmlEntityOKList);
        
      }

      messageXmlEntityOK.setBOX(boxXmlEntityOK);
      return messageXmlEntityOK;
    }
    
    
    private List<TwydCellXmlEntitySC> configXmlSc(String palletId,
        Map<String, Ret_cus_box> mtrlBoxMap, Ret_box retBox, List<Ret_prd_info> retPrdInfoList) {
    	Collections.sort(retPrdInfoList);
      List<TwydCellXmlEntitySC> cellXmlEntitySCList = new ArrayList<TwydCellXmlEntitySC>();

      for (Ret_prd_info retPrdInfo : retPrdInfoList) {
        String sheetId = retPrdInfo.getPrd_seq_id();
        if (StringUtils.contains(sheetId, "_")) {
          sheetId = sheetId.split("_")[0];
        }
        List<Ret_cus_prd> retCusPrdList = retCusPrdDao.getPrdList(sheetId);
        
        TwydCellXmlEntitySC cellXmlEntitySC = new TwydCellXmlEntitySC();
        
        
        cellXmlEntitySC.setCELLSIZE("");//14.1 产品尺寸
        cellXmlEntitySC.setITEMNO("");//良品、可出货报废回传沃格产后型号， IQC NG 回传客户的来料型号
        cellXmlEntitySC.setMODEL_NO("");//A030JAN01.4 客户机种，回传 AUO 的值
        cellXmlEntitySC.setMODULE_SITE("DW");
        cellXmlEntitySC.setCELLSITE("");
        cellXmlEntitySC.setBOXNO("Z0F");
          
        if (!retCusPrdList.isEmpty()) {
          List<Ret_cus_box> retCusBoxList = retCusBoxDao.getMtrlBox(retCusPrdList.get(0).getBoxid());
          if (!retCusBoxList.isEmpty()) {
            cellXmlEntitySC.setCELLSIZE(retCusBoxList.get(0).getCellsize());//14.1 产品尺寸
            cellXmlEntitySC.setITEMNO(retCusBoxList.get(0).getItemno());
            cellXmlEntitySC.setMODEL_NO(retCusBoxList.get(0).getModel_no());//A030JAN01.4 客户机种，回传 AUO 的值
            cellXmlEntitySC.setCELLSITE(retCusBoxList.get(0).getCellsite());
            cellXmlEntitySC.setBOXNO("Z0F");
          }
        }
        
        if (!retCusPrdList.isEmpty() && retCusPrdList.get(0) != null) {
          cellXmlEntitySC.setWO_ID(retCusPrdList.get(0).getWo_id());
        }else {
          cellXmlEntitySC.setWO_ID("");
        }
        cellXmlEntitySC.setSHEETNO(sheetId);
        if (!retCusPrdList.isEmpty() && retCusPrdList.get(0) != null) {
          cellXmlEntitySC.setCELLGRADE(retCusPrdList.get(0).getCellgrade());
        }else {
          cellXmlEntitySC.setCELLGRADE("");
        }
        if (!retCusPrdList.isEmpty() && retCusPrdList.get(0) != null) {
          cellXmlEntitySC.setLOTTYPE(retCusPrdList.get(0).getLottype());
        }else {
          cellXmlEntitySC.setLOTTYPE("");
        }
        cellXmlEntitySC.setCHIPGRADE("X");
        if (!retCusPrdList.isEmpty() && retCusPrdList.get(0) != null) {
          cellXmlEntitySC.setQTY(retCusPrdList.get(0).getQty());
        }else {
          cellXmlEntitySC.setQTY("");
        }
        cellXmlEntitySC.setSCRAP_RESPONSIBILITY("I".equals(retPrdInfo.getRsn_dept1()) ? "A":"B");
        cellXmlEntitySC.setSCRAP_AREA("LR");
        cellXmlEntitySC.setSCRAP_TIME(TimeUtil.getEvtTime());
        
        cellXmlEntitySCList.add(cellXmlEntitySC);
        
      }

      return cellXmlEntitySCList;
    }
}
